<template>
  <div>
    <el-container>
      <el-scrollbar style="height: 610px">
        <el-header style="height: 100%">
          <el-card>
            <el-form :model="populationInfo">
              <el-form-item label="身份证号" style="margin-left: 35%">
                <el-input v-model="searchIdNumber" placeholder="请输入立户人身份证号" style="width: 200px;" />
                <el-form-item style="margin-left: 50px">
                  <el-button type="primary" @click="searchInfo">搜索</el-button>
                </el-form-item>
              </el-form-item>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="编号" label-width="100">
                    <el-input v-model="populationInfo.personId" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="姓名" label-width="100">
                    <el-input v-model="populationInfo.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性别" label-width="100">
                    <el-input v-model="populationInfo.gender" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="出生日期" label-width="100">
                    <el-input v-model="populationInfo.birthDate" :disabled="true"
                      :value="populationInfo.birthDate ? new Date(populationInfo.birthDate).toLocaleDateString() : ''" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="身份证号" label-width="100">
                    <el-input v-model="populationInfo.idNumber" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="家庭户号" label-width="100">
                    <el-input v-model="populationInfo.householdNumber" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="与户主关系" label-width="100" :formatter="relationToHeadFormatter">
                    <el-input v-model="populationInfo.relationToHead" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="婚姻状况" label-width="100" :formatter="maritalStatusFormatter">
                    <el-input v-model="populationInfo.maritalStatus" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="教育程度" label-width="100" :formatter="educationLevelFormatter">
                    <el-input v-model="populationInfo.educationLevel" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="职业" label-width="100">
                    <el-input v-model="populationInfo.occupation" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="电话号码" label-width="100">
                    <el-input v-model="populationInfo.phoneNumber" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="民族" label-width="100">
                    <el-input v-model="populationInfo.ethnicity" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="是否残疾" label-width="100" :formatter="isDisabledFormatter" prop="isDisabled">
                    <el-select v-model="populationInfo.isDisabled" placeholder="请选择婚姻情况" style="width:100%" filterable
                      disabled>
                      <el-option label="残疾" value="1" />
                      <el-option label="不残疾" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="血型" label-width="100" :formatter="bloodTypeFormatter" prop="bloodType">
                    <el-select v-model="populationInfo.bloodType" placeholder="请选择婚姻情况" style="width:100%" filterable
                      disabled>
                      <el-option label="A" value="1" />
                      <el-option label="B" value="2" />
                      <el-option label="AB" value="3" />
                      <el-option label="O" value="4" />
                      <el-option label="其他" value="5" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="服兵役状况" label-width="100" :formatter="militaryStatusFormatter"
                    prop="militaryStatus">
                    <el-select v-model="populationInfo.militaryStatus" placeholder="请选择婚姻情况" style="width:100%"
                      filterable disabled>
                      <el-option label="未服兵役" value="1" />
                      <el-option label="现役" value="2" />
                      <el-option label="退役" value="3" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="户籍住址" label-width="100" prop="householdAddress">
                    <el-input v-model="populationInfo.household.registeredAddress" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
          <el-card>
            <el-form :model="householdsInfo" label-width="120px">
              <h3>家庭户口立户</h3>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="户号">
                    <el-input v-model="householdsInfo.householdNumber" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="户主ID">
                    <el-input v-model="householdsInfo.headId" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="户籍住址">
                    <el-input v-model="householdsInfo.registeredAddress" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="派出所">
                    <el-input v-model="officerInfo.policeStation.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建时间">
                    <template #default="scope">
                      <el-date-picker v-model="householdsInfo.createdAt" type="date" placeholder="选择日期">
                      </el-date-picker>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item style="float: right;">
                <el-button type="primary" @click="submitForm">户口立户</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-header>
        <el-main>
          <h3>户口表</h3>
          <el-card style="margin: 0 auto;">
            <el-table :data="tableData" style="width: 100%" text-align: center border>
              <el-table-column prop="householdNumber" label="家庭户号" width="100"></el-table-column>
              <el-table-column prop="name" label="姓名" width="100"></el-table-column>
              <el-table-column prop="idNumber" label="身份证号" width="150"></el-table-column>
              <el-table-column prop="registeredAddress" label="户籍住址" width="250"></el-table-column>
              <!-- <el-table-column prop="policeStationId" label="派出所ID" width="150"></el-table-column> -->
              <el-table-column prop="policeStation" label="派出所" width="150"></el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="300">
                <template #default="scope">
                  <el-date-picker v-model="scope.row.createdAt" type="date" placeholder="选择日期"
                    disabled></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button type="success" size="small" @click="editHousehold(scope.row)">编辑</el-button>
                  <el-button type="warning" size="small" @click="confirmDeleteHousehold(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="display: flex; justify-content: center;">
              <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
          </el-card>
        </el-main>

      </el-scrollbar>
    </el-container>
    <!-- 户口弹窗 -->
    <el-dialog v-model="dialoghouseholdFormVisible" :title="title" width="950">
      <el-form :model="householdsInfo">
        <el-form-item label="家庭户号" label-width="80">
          <el-input v-model="householdsInfo.householdNumber" disabled />
        </el-form-item>
        <el-form-item label="户籍住址" label-width="80">
          <el-input v-model="householdsInfo.registeredAddress" />
        </el-form-item>
        <!-- <el-form-item label="派出所" label-width="80">
          <el-input v-model="householdsInfo.policeStation" disabled/>
        </el-form-item> -->
        <el-form-item label="创建时间" label-width="80">
          <template #default="scope">
            <el-date-picker v-model="householdsInfo.createdAt" type="date" placeholder="选择日期" disabled>
            </el-date-picker>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialoghouseholdFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submithouseholdForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>

import { ref, reactive, onMounted } from 'vue';
import { getHouseholdPage, updateHousehold, deleteHousehold, addHousehold, getPopulation } from '@/api/household';
import { getPopulationByIdNumber } from '@/api/population';
import { ElMessage, ElMessageBox } from 'element-plus';
import { updatePopulation } from '../../../api/population';
import { useStore } from 'vuex';
import { getPoliceOfficerPage } from '@/api/police';
const store = useStore();
const userName = store.getters.userName;
const officerInfo = store.getters.officerInfo;

const dialoghouseholdFormVisible = ref(false);
const title = ref('添加户口');
const householdsInfo = reactive({
  householdNumber: '',
  headId: '',
  registeredAddress: '',
  policeStationId: '',
  createdAt: '',
});
const populationInfo = reactive({
  personId: '',
  name: '',
  gender: '',
  birthDate: '',
  idNumber: '',
  householdNumber: '',
  relationToHead: '',
  maritalStatus: '',
  educationLevel: '',
  occupation: '',
  phoneNumber: '',
  isAlive: '',
  ethnicity: '',
  household: {
    registeredAddress: '',
  }
});

const searchIdNumber = ref('');
const searchInfo = async () => {
  title.value = "搜索个人信息";
  const { data } = await getPopulationByIdNumber({ idNumber: searchIdNumber.value });
  if (!data.data) {
    ElMessage.error("请输入正确信息");
  } else {
    Object.assign(populationInfo, data.data);
    householdsInfo.headId = populationInfo.personId;
    const total = await sethouseholdId();
    householdsInfo.householdNumber = total;
    ElMessage.success('查询成功');
    console.log(householdsInfo);
  }
}
const sethouseholdId = async () => {
  const { data } = await getHouseholdPage({
    currentPage: 1,
    pageSize: 999,
    headId: ''
  });
  if (data.data.length !== 0) {
    const lastHousehold = data.data[data.data.length - 1];
    return lastHousehold.householdNumber + 1; // 返回新的户号
  } else {
    return 1; // 如果没有数据，返回1
  }

}
const submitForm = async () => {
  title.value = "添加户口"
  if (populationInfo.isAlive === "存活") {
    if (populationInfo.relationToHead === "户主") {
      ElMessage.error('此人已经为户主');
      fetchData();
    }
    else {
      householdsInfo.policeStationId=officerInfo.policeStation.stationId;
      await addHousehold(householdsInfo);
      populationInfo.householdNumber = householdsInfo.householdNumber;
      populationInfo.relationToHead = "户主";  
      await updatePopulation(populationInfo);
      ElMessage.success('立户成功');

    }
  } else {
    ElMessage.error('该人已销户');
  }
}
//多表连查
const fetchData = async () => {
  try {
    // 获取家庭户口数据
    const { data: pageData } = await getHouseholdPage({
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      householdNumber: searchParams.householdNumber
    });
    pagination.total = pageData.total;

    // 创建一个用于存储整合后数据的数组
    const integratedData = [];

    // 遍历家庭户口数据
    for (const household of pageData.data) {
      // 异步获取对应的户主个人信息
      const { data: populationData } = await getPopulation({ personId: household.headId });

      // 使用Object.assign()合并对象，确保headId和personId视为同一属性
      const combinedItem = Object.assign({}, populationData.data, { headId: household.headId }, household);

      // 将合并后的对象添加到整合后数据的数组中
      integratedData.push(combinedItem);

    }
    // 更新表格数据
    tableData.value = integratedData;
    for (let i = 0; i < tableData.value.length; i++) {
      tableData.value[i].policeStation = tableData.value[i].policeStation.name;
    }
  } catch (error) {
    ElMessage.error('获取数据失败');
    console.error(error);
  }
};
const searchParams = reactive({
  headId: ''
});
const deleteUser = async (row) => {
  await deleteHousehold(row.householdNumber);
  populationInfo.householdNumber = '';
  await updatePopulation(populationInfo);
  ElMessage.success('删除成功');
  fetchData();
};
const confirmDeleteHousehold = (row) => {
  ElMessageBox.confirm(`确定要删除 ${row.headId} 户口吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(row);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
const tableData = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

//废除的单独查询户口表
const refetchData = async () => {
  // 获取家庭户口数据
  const { data } = await getHouseholdPage({
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
    householdNumber: searchParams.householdNumber
  });
  tableData.value = data.data;
  pagination.total = data.total;
}
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchData();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchData();
};
const editHousehold = async (row) => {
  dialoghouseholdFormVisible.value = true;
  title.value = '编辑户口';
  Object.assign(householdsInfo, row);
};
const submithouseholdForm = async () => {
  dialoghouseholdFormVisible.value = false;
  //设置policeStation为null
  householdsInfo.policeStation = null;
  ElMessage.success('更新成功');
  // 更新户口信息逻辑
  await updateHousehold(householdsInfo);
  fetchData();
};


onMounted(() => {
  fetchData();
});

</script>
<style scoped>
/* 添加外边距到每个el-card */
.el-card {
  margin-bottom: 20px;
  /* 可以根据需要调整这个值 */
}

h3 {
  text-align: center;
}

.example-pagination-block+.example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>
